package it.milanoeasy.gae;

import it.milanoeasy.jdoBeans.ClientBean;
import it.milanoeasy.jdoBeans.EdicolaBean;
import it.milanoeasy.utils.MECrypt;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;


public class RegisterServlet extends GenericServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6502440891561296045L;
	public static final int FIXED_LEN = 20;
	public static final String FIXED_STRING = "MEP10";

	
	static public String createHalfStringForClientID(HttpServletRequest request) {
		String userAgent=request.getHeader("User-Agent");
		String remoteAddr=request.getRemoteAddr();		
		String inputString=FIXED_STRING+remoteAddr+" "+userAgent;
		inputString=MECrypt.normalize(inputString,FIXED_LEN,true);				
		return inputString;
	}
	
	 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {				
		String clientId=null;		
		//logHeaderValues(request);
		String userAgent=request.getHeader("User-Agent");
		String remoteAddr=request.getRemoteAddr();
		
		ClientBean newClientBean=saveNewClientBean(userAgent,remoteAddr);
		System.out.println("salvato oggetto con id:"+newClientBean.getClientId());
		HttpSession session=request.getSession();
		session.setAttribute("client", newClientBean);
		
		String inputString = createStringForClientId(request,newClientBean);
		try {
			clientId=MECrypt.getClientId(inputString);
		} catch (Exception e) {			
			e.printStackTrace();
		}
		//getServletContext().getRequestDispatcher("/register.jsp").forward(request,response);
		PrintWriter out = response.getWriter();out.println(clientId);out.flush();
	}


	private ClientBean saveNewClientBean(String userAgent,String remoteAddr) {
		
		//getPersistenceManager().currentTransaction().begin();
		
		ClientBean cb=null;
		cb=new ClientBean();
		cb.setUseragent(userAgent);
		cb.setIp(remoteAddr);
		
		//DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        //datastore.put(cb);
        
		try {
			getPersistenceManager().makePersistent(cb);
			//getPersistenceManager().currentTransaction().commit();
		} finally {
//			if (getPersistenceManager().currentTransaction().isActive()) {
//		        getPersistenceManager().currentTransaction().rollback();
//		    }
			getPersistenceManager().close();
		}
				
		
		getPersistenceManager().close();	
		return cb;
	}


			
	private String createStringForClientId(HttpServletRequest request,ClientBean cb) {
		String inputString = createHalfStringForClientID(request);
		//inputString+=MECrypt.randomString(10);
		inputString+=MECrypt.normalize(""+cb.getClientId(),FIXED_LEN,false);
		return inputString;
	}
	

	
	
	
	/*
	private void logHeaderValues(HttpServletRequest request) {
		Enumeration headerNames=request.getHeaderNames();
		String headerName=null,headerValue=null,result="";
		while (headerNames.hasMoreElements()){
			headerName=(String) headerNames.nextElement();
			headerValue=request.getHeader(headerName);
			result+=headerName+":="+headerValue;
			System.out.println(headerName+":="+headerValue);
		}
	}
	*/
}
